package com.example.administrator.demo_picdownload;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Handler;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    private EditText et1;
    private ImageView iv1;
    private static String TAG="TEST";
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            Bitmap bitmap=(Bitmap) msg.obj;
            iv1.setImageBitmap(bitmap);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et1=findViewById(R.id.et1);
        iv1=findViewById(R.id.iv1);
    }
    public void pic_download(View view){
        final String path=et1.getText().toString().trim();
        new Thread(){
            public void run(){
                try {
                    Log.i(TAG,"START");
                    URL url=new URL(path);
                    HttpURLConnection conn=(HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(3000);
                    String type=conn.getContentType();
                    int len=conn.getContentLength();
                    int code=conn.getResponseCode();
                    Log.i(TAG,"状态码:"+code+"图片大小:"+len+"文件类型:"+type);
                    if (code==200){
                        InputStream is=conn.getInputStream();
                        Bitmap bitmap= BitmapFactory.decodeStream(is);
                        Message msg=Message.obtain();
                        msg.obj=bitmap;
//                        msg.what=1;
                        handler.sendMessage(msg);
                        is.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i(TAG,"GG");
                }
            }
        }.start();
    }
}
